package leetcode.link;

public class Test0207 {

    // 1,2,5,6,7
    // 3,4,5,6,7
//    给你两个单链表的头节点 headA 和 headB ，请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点，返回 null 。
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        int lengthA = 1;
        int lengthB = 1;
        ListNode temp = headA;
        while (temp.next != null) {
            temp = temp.next;
            lengthA++;
        }
        temp = headB;
        while (temp.next != null) {
            temp = temp.next;
            lengthB++;
        }
        if (lengthA > lengthB) {
            int n = lengthA - lengthB;
            for (int i = 1; i <= n; i++) {
                headA = headA.next;
            }
        } else if (lengthA < lengthB) {
            int n = lengthB - lengthA;
            for (int i = 1; i <= n; i++) {
                headB = headB.next;
            }
        }
        while (headA != null) {
            if (headA == headB) {
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
}
